<template>
  <div class="workflow-detail" v-loading="loading">
    <template v-if="workflow">
      <div class="header">
        <div class="title-section">
          <h2>{{ workflow.title }}</h2>
          <div class="tags">
            <el-tag
              v-for="tag in workflow.tags"
              :key="tag"
              size="small"
              effect="plain"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>

        <div class="actions">
          <el-button-group>
            <el-button @click="back">返回</el-button>
            <el-button
              v-if="canManage"
              type="primary"
              @click="editWorkflow"
            >
              编辑
            </el-button>
            <el-button
              type="primary"
              @click="showExecuteDialog"
            >
              执行
            </el-button>
          </el-button-group>
        </div>
      </div>

      <div class="content">
        <el-row :gutter="24">
          <el-col :span="16">
            <el-card class="detail-card">
              <template #header>
                <div class="card-header">
                  <span>工作流详情</span>
                </div>
              </template>

              <div class="detail-info">
                <div class="info-item">
                  <span class="label">工作流ID：</span>
                  <span>{{ workflow.id }}</span>
                </div>
                <div class="info-item">
                  <span class="label">工作流类型：</span>
                  <span>{{ getWorkflowType(workflow.type) }}</span>
                </div>
                <div class="info-item">
                  <span class="label">创建时间：</span>
                  <span>{{ formatDate(workflow.createdAt) }}</span>
                </div>
                <div class="info-item">
                  <span class="label">更新时间：</span>
                  <span>{{ formatDate(workflow.updatedAt) }}</span>
                </div>
                <div class="info-item">
                  <span class="label">算力消耗：</span>
                  <span>{{ workflow.powerConsumption || '无' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">是否公开：</span>
                  <el-tag :type="workflow.isPublic ? 'success' : 'info'" size="small">
                    {{ workflow.isPublic ? '是' : '否' }}
                  </el-tag>
                </div>
              </div>

              <div class="description">
                <h4>工作流描述</h4>
                <p>{{ workflow.description || '暂无描述' }}</p>
              </div>

              <div class="detail-image" v-if="workflow.detailImage">
                <h4>详细说明</h4>
                <img :src="workflow.detailImage" alt="详细说明" />
              </div>

              <div class="samples" v-if="workflow.samples?.length">
                <h4>示例展示</h4>
                <el-carousel :interval="4000" type="card" height="300px">
                  <el-carousel-item v-for="sample in workflow.samples" :key="sample">
                    <img :src="sample" :alt="workflow.title" />
                  </el-carousel-item>
                </el-carousel>
              </div>
            </el-card>
          </el-col>

          <el-col :span="8">
            <el-card class="history-card">
              <template #header>
                <div class="card-header">
                  <span>执行历史</span>
                  <el-button link @click="showHistoryDrawer">
                    查看全部
                  </el-button>
                </div>
              </template>

              <div class="history-list">
                <div
                  v-for="record in recentHistory"
                  :key="record.id"
                  class="history-item"
                >
                  <div class="time">{{ formatDate(record.startTime) }}</div>
                  <div class="status">
                    <el-tag :type="getStatusType(record.status)" size="small">
                      {{ getStatusText(record.status) }}
                    </el-tag>
                  </div>
                  <div class="progress">
                    <el-progress
                      :percentage="record.progress"
                      :status="getProgressStatus(record.status)"
                    />
                  </div>
                </div>

                <div v-if="!recentHistory.length" class="empty-tip">
                  暂无执行记录
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 执行对话框 -->
      <el-dialog
        v-model="executeDialog.visible"
        :title="workflow.title"
        width="800px"
        destroy-on-close
      >
        <dynamic-workflow
          v-if="executeDialog.visible"
          :workflow-id="workflow.id"
          :template="template"
          @success="handleExecuteSuccess"
        />
      </el-dialog>

      <!-- 历史记录抽屉 -->
      <workflow-history-drawer
        v-model="historyDrawer.visible"
        :workflow-id="workflow.id"
      />
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { useWorkflowStore } from '@/stores/workflow'
import DynamicWorkflow from '@/components/DynamicWorkflow.vue'
import WorkflowHistoryDrawer from '@/components/WorkflowHistoryDrawer.vue'
import dayjs from 'dayjs'
import type { Workflow, WorkflowTemplate } from '@/types/workflow'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const workflowStore = useWorkflowStore()

// 工作流数据
const loading = ref(false)
const workflow = ref<Workflow | null>(null)
const template = ref<WorkflowTemplate | null>(null)
const recentHistory = ref<any[]>([])

// 对话框状态
const executeDialog = ref({
  visible: false
})

const historyDrawer = ref({
  visible: false
})

// 计算属性
const canManage = computed(() => {
  return workflow.value?.userId === userStore.user?.id
})

// 加载工作流数据
const loadWorkflow = async () => {
  try {
    loading.value = true
    const id = route.params.id as string
    const [workflowData, templateData, historyData] = await Promise.all([
      workflowStore.getWorkflow(id),
      workflowStore.getWorkflowTemplate(id),
      workflowStore.getWorkflowHistory(id, { limit: 5 })
    ])

    workflow.value = workflowData
    template.value = templateData
    recentHistory.value = historyData
  } catch (error: any) {
    ElMessage.error(error.message || '加载工作流失败')
    router.push({ name: 'workflow' })
  } finally {
    loading.value = false
  }
}

// 工作流类型
const getWorkflowType = (type: string) => {
  const types: Record<string, string> = {
    image: '图像生成',
    process: '图像处理',
    text: '文本生成'
  }
  return types[type] || type
}

// 状态相关
const getStatusType = (status: string) => {
  switch (status) {
    case 'completed':
      return 'success'
    case 'failed':
      return 'danger'
    case 'running':
      return 'warning'
    default:
      return 'info'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'completed':
      return '已完成'
    case 'failed':
      return '失败'
    case 'running':
      return '执行中'
    default:
      return '等待中'
  }
}

const getProgressStatus = (status: string) => {
  switch (status) {
    case 'completed':
      return 'success'
    case 'failed':
      return 'exception'
    case 'running':
      return ''
    default:
      return ''
  }
}

// 格式化日期
const formatDate = (date: string | Date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 编辑工作流
const editWorkflow = () => {
  router.push({
    name: 'workflow-edit',
    params: { id: workflow.value!.id }
  })
}

// 显示执行对话框
const showExecuteDialog = () => {
  executeDialog.value.visible = true
}

// 显示历史记录
const showHistoryDrawer = () => {
  historyDrawer.value.visible = true
}

// 执行成功回调
const handleExecuteSuccess = () => {
  executeDialog.value.visible = false
  loadWorkflow()
}

// 返回列表
const back = () => {
  router.back()
}

onMounted(() => {
  loadWorkflow()
})
</script>

<style scoped lang="scss">
.workflow-detail {
  padding: 24px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 24px;

    .title-section {
      h2 {
        margin: 0 0 8px;
      }

      .tags {
        .el-tag {
          margin-right: 8px;
        }
      }
    }
  }

  .content {
    .detail-card,
    .history-card {
      margin-bottom: 24px;

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
    }

    .detail-info {
      margin-bottom: 24px;

      .info-item {
        margin-bottom: 12px;
        display: flex;
        align-items: center;

        .label {
          color: #666;
          margin-right: 8px;
          min-width: 100px;
        }
      }
    }

    .description {
      margin-bottom: 24px;

      h4 {
        margin: 0 0 12px;
        color: #333;
      }

      p {
        margin: 0;
        color: #666;
        line-height: 1.6;
      }
    }

    .detail-image {
      margin-bottom: 24px;

      h4 {
        margin: 0 0 12px;
        color: #333;
      }

      img {
        max-width: 100%;
        border-radius: 4px;
      }
    }

    .samples {
      h4 {
        margin: 0 0 12px;
        color: #333;
      }

      :deep(.el-carousel__item) {
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          border-radius: 4px;
        }
      }
    }

    .history-list {
      .history-item {
        padding: 12px;
        border-bottom: 1px solid #eee;

        &:last-child {
          border-bottom: none;
        }

        .time {
          margin-bottom: 8px;
          color: #666;
          font-size: 12px;
        }

        .status {
          margin-bottom: 8px;
        }
      }

      .empty-tip {
        padding: 24px;
        text-align: center;
        color: #999;
      }
    }
  }
}
</style> 